package com.example.kerberostest;

import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.security.UserGroupInformation;

import java.io.File;
import java.io.IOException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.Configuration;


public class TestHDFS {
    public static void main(String[] args) throws IOException {
        // 设置 Kerberos 相关配置
        System.setProperty("java.security.krb5.conf", "src/main/resources/krb5.conf");
        // 创建 HDFS 配置对象
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://master.tobehacker.com:9000");
        conf.set("hadoop.security.authentication", "kerberos");
        conf.set("hadoop.rpc.protection", "authentication");
        // 使用 keytab 进行 Kerberos 认证
        UserGroupInformation.setConfiguration(conf);
        File hdfsKeytabFile = new File(TestHDFS.class.getClassLoader().getResource("tust.keytab").getFile());
        UserGroupInformation.loginUserFromKeytab("tust@TOBEHACKER.COM", hdfsKeytabFile.getAbsolutePath());

        // 创建 HDFS 文件系统对象
        FileSystem fs = FileSystem.get(conf);

        // 列出 HDFS 根目录下的文件和目录
        FileStatus[] fsStatus = fs.listStatus(new Path("/"));
        for (int i = 0; i < fsStatus.length; i++) {
            System.out.println("+++++ "+fsStatus[i].getPath().toString());
        }

        // 关闭 HDFS 文件系统对象
        fs.close();
    }


}
